package com.sxjh.service.impl;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.resource.InputStreamResource;
import cn.hutool.core.io.resource.MultiResource;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sxjh.common.Constant;
import com.sxjh.common.ResultException;
import com.sxjh.entity.ConfigEntity;
import com.sxjh.entity.Intrude;
import com.sxjh.entity.param.IntruduListParam;
import com.sxjh.entity.result.IntruduListResult;
import com.sxjh.entity.result.PhpUpLoadResult;
import com.sxjh.mapper.IntruduMapper;
import com.sxjh.service.IntruduService;
import com.sxjh.socket.AppStarSocketServer;
import com.sxjh.socket.StarSocketServer;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class IntruduServiceImpl extends ServiceImpl<IntruduMapper, Intrude> implements IntruduService {

    @Autowired
    private IntruduMapper intruduMapper;

    @Autowired
    private ConfigEntity configEntity;

    @Override
    public IPage<IntruduListResult> list(IPage iPage, IntruduListParam param) {
        return intruduMapper.list(iPage, param);
    }

    @Override
    public void receipt(List<Integer> ids) {
        intruduMapper.receipt(ids);
    }

    //    @Async(value = "taskExecutor")
    @Override
    public void pushNotice() {
        IPage<Intrude> iPage = new Page(1, 30);
        LambdaQueryWrapper<Intrude> queryWrapper = new LambdaQueryWrapper<>();
        //只查询未读的消息
        queryWrapper.eq(Intrude::getReaded, 2);
        queryWrapper.orderByDesc(Intrude::getCreatedAt);
        iPage = page(iPage, queryWrapper);
        if (iPage != null && CollUtil.isNotEmpty(iPage.getRecords())) {
            String message = JSON.toJSONString(iPage.getRecords());
            try {
                StarSocketServer.sendInfo(message, null);
                AppStarSocketServer.sendInfo(message, null);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    @Override
    @Async(value = "taskExecutor")
    public String getFilePath(String srcpicData, Integer id) {
        if (StringUtils.isBlank(srcpicData)) return "";

        // 解析base64原文件, 转成输入流
        if (srcpicData.contains("data:image/png;base64,")) {
            int index = srcpicData.indexOf(",");
            if (index != -1) {
                srcpicData = srcpicData.substring(index + 1, srcpicData.length());
            }
        }

        java.io.File file = new File(configEntity.getFolder() + "\\" + IdUtil.simpleUUID() + ".png");
        FileInputStream inputStream = null;
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
            Base64.decodeToFile(srcpicData, file);
            inputStream = new FileInputStream(file);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        // 保存图片上传PHP服务器，返回服务器url
        MultiResource multiResource = new MultiResource(new InputStreamResource(inputStream, file.getName()));
        String url = configEntity.getAddress() + "/api/fileUpload";
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "multipart/form-data");
        String result = HttpUtil.createPost(url).addHeaders(headers).timeout(100000).form("file", multiResource).execute().body();
        if (StrUtil.isNotBlank(result)) {
            PhpUpLoadResult phpUpLoadResult = JSON.parseObject(result, PhpUpLoadResult.class);
            if (phpUpLoadResult != null) {
                PhpUpLoadResult.Status status = phpUpLoadResult.getStatus();
                if (status != null && status.getErrCode() == 0) {
                    PhpUpLoadResult.Data data = phpUpLoadResult.getData();
                    if (data != null) {
                        // 异步更新图片信息
                        Intrude intrude = new Intrude();
                        intrude.setImg1("/storage/uploadfile/" + data.getPath());
                        intrude.setId(id);
                        intruduMapper.updateById(intrude);
                    }
                } else {
                    try {
                        throw new ResultException(status.getMessage());
                    } catch (ResultException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }
        file.delete();

        // 异步推送消息
        pushNotice();
        // 设置未读开锁列表查询参数
        IntruduListParam param = new IntruduListParam();
        param.setIsPush(2);
        param.setReaded(2);
        // 查询未读开锁列表
        IPage<IntruduListResult> iPage = new Page(param.getCurrent(), param.getSize());
        if (param.getSize() == -1) {
            iPage.setSize(Constant.maxSize);
        }
        iPage = intruduMapper.list(iPage, param);
        if (iPage != null) {
            List<IntruduListResult> records = iPage.getRecords();
            records.forEach(t -> {
                // 更新开锁推送状态
                Intrude intrude1 = new Intrude();
                intrude1.setIsPush(1);
                intrude1.setId(t.getId());
                intruduMapper.updateById(intrude1);
            });
        }

        return "";
    }

}
